import React, { memo } from 'react';
import { Redirect, RouteComponentProps } from 'react-router-dom';
import config from '../config';
import store from '../store';
import { getToken } from '../utils/cookie';
import { businessRoutes } from '../utils/routes';
import { IRoute } from '../types/route';

interface AuthProps extends RouteComponentProps {
  route: IRoute;
  children: React.ReactNode;
}

function checkAuth(location: RouteComponentProps['location']): boolean {
  // redux中的routes 同时负责渲染侧边栏
  const { flattenRoutes } = store.getState().app;

  // 判断当前访问的路由是否在业务路由中，不是走404
  const route = businessRoutes.find((child) => child.path === location.pathname);

  if (!route) return true;

  if (route.redirect) return true;

  if (!route.auth) return true;

  // 查看该用户是否有路由权限
  if (!flattenRoutes.find((child) => child.path === location.pathname)) return false;

  return true;
}

const Auth: React.FC<AuthProps> = (props: AuthProps) => {
  // 未登录
  if (!getToken()) {
    return (
      <Redirect
        to={`/login?redirectURL=${encodeURIComponent(
          window.location.origin + config.BASENAME + props.location.pathname + props.location.search,
        )}`}
      />
    );
  }

  // 检查授权
  if (!checkAuth(props.location)) {
    return <Redirect to="/403" push />;
  }

  if (props.route.redirect) {
    return <Redirect to={props.route.redirect!} push />;
  }

  return <>{props.children}</>;
};

export default memo(Auth);
